<?php
namespace Beerus\Modules\DecoCompanyPreferential\Controllers;

use App\Pockets\GridDataModel as pGridDataModel;
use Doraemon\cache\Queue;
use Doraemon\model\DecoCompany;
use Doraemon\model\DecoCompany\DecoCompanyPreferentialActivity;
use Doraemon\model\DecoCompany\DecoCompanyPreferentialAudit;
use Doraemon\model\DecoCompanyAuth;
use Doraemon\model\DesignerGreetingsSet;
use Doraemon\model\Member;
use Doraemon\service\User;
use Doraemon\tools\ShopArea;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Grid\Displayers\DropdownActions;
use Encore\Admin\Layout\Content;
use Encore\Admin\Widgets\Tab;
use Illuminate\Http\Request;
use Illuminate\Support\MessageBag;
use Doraemon\tools\ImgUrl;
use Encore\Admin\Widgets\Form;
use Doraemon\service\DecoCompany\DecoCompany as sDecoCompany;
use Medoo\Medoo;

class IndexController
{
	const PAGE_SIZE = 20;
    const CHECK_STATUS_DESC = [
        DecoCompanyPreferentialActivity::CHECK_WAIT => "待审核",
        DecoCompanyPreferentialActivity::CHECK_PASS => "通过",
        DecoCompanyPreferentialActivity::CHECK_FAIL => "不通过"
    ];

	// 列表
	public function index(Request $request,Content $content)
	{
		Admin::style('.col-md-8{width: 80%}');
		$params = $request->all();
		$page_size = $request->input('per_page', self::PAGE_SIZE);
		$page = $request->input('page', 1);

		$condition = [];
		if (!empty($params['uid'])) {
			$condition['uid'] = $params['uid'];
		}

		if (!empty($params['nick'])) {
			$uid = User::getUidByNick($params['nick']);
			$condition['uid'] = $uid;
		}

		if (!empty($params['activity_status'])) {
			$condition['activity_status'] = $params['activity_status'];
		}

		if (!empty($params['activity_type'])) {
			$condition['activity_type'] = $params['activity_type'];
		}

        if (!empty($params['is_superior'])) {
            $condition['is_superior'] = $params['is_superior'];
        }

        if (isset($params['check_status']) && $params['check_status']!='') {
            $condition['check_status'] = $params['check_status'];
        }

        if (!empty($params['area_id'])) {
            $uids = DecoCompany::select('uid', ['main_area_code'=>$params['area_id']]);
            $uids = $uids ? $uids : [];
            if(!empty($uids)){
                $condition['uid'] = $uids;
            }

        }

		$total = DecoCompanyPreferentialActivity::count($condition);

		$lists = [];
        $cityArr = [];
		if (!empty($total)) {
            //获取装修公司下的所有城市
            $allUids = DecoCompanyPreferentialActivity::select("uid",[]);
            $allUids = $allUids ? $allUids : [];
            $conditionNew['uid'] = $allUids;
            $decoList = DecoCompany::select(['main_area_code','main_area_name','uid'],$conditionNew);
            $cityArr = array_column($decoList,'main_area_name','main_area_code');
            $allCityList = array_column($decoList,'main_area_name','uid');
			$condition['ORDER'] = Medoo::raw('GREATEST(created_at, updated_at) DESC');
			$condition['LIMIT'] = [
				($page - 1) * $page_size,
				$page_size
			];
			$lists = DecoCompanyPreferentialActivity::select('*', $condition);
			$user_ids = array_column($lists, 'uid');
			$member_info = Member::getUsers($user_ids);
//			$auth = DecoCompanyAuth::select(['uid', 'enterprise_name'], [
//				'uid' => $user_ids
//			]);
//			$map_company = array_column($auth, 'enterprise_name', 'uid');

			foreach ($lists as &$item) {
//				$item['enterprise_name'] = empty($map_company[$item['uid']]) ? '' : $map_company[$item['uid']];
				$item['nick'] = empty($member_info[$item['uid']]['nick']) ? '-' : $member_info[$item['uid']]['nick'];
				$mainArea = $allCityList[$item['uid']];
                $item['city_name'] = '';
				if(!empty($mainArea)){
                    $item['city_name'] = $mainArea;
                }
				$item['activity_type'] = DecoCompanyPreferentialActivity::ACTIVITY_TYPE[$item['activity_type']];
				$item['activity_status'] = DecoCompanyPreferentialActivity::ACTIVITY_STATUS[$item['activity_status']];
				$item['effect_date'] = $item['start_date'] .' 至 '. $item['end_date'];
				$item['data_status'] = DecoCompanyPreferentialActivity::DATA_STATUS[$item['data_status']];
				$last_edit_time = $item['updated_at'] ?: $item['created_at'];
				$item['last_edit_time'] = !empty($last_edit_time) ? date('Y-m-d H:i:s', $last_edit_time) : '-';
                $item['check_status'] = DecoCompanyPreferentialActivity::CHECK_STATUS[$item['check_status']];
			}
			unset($item);
		}

		$gridModel = new pGridDataModel($lists, $total, [
			'perPage' => self::PAGE_SIZE
		]);
		$gridList = Admin::grid($gridModel,
			function (Grid $grid) use ($gridModel,$cityArr) {
				$grid->paginate($gridModel->getPerPage());
				$grid->disableExport();
				$grid->disableRowSelector();
				$grid->disableCreateButton();

				$grid->filter(function (Grid\Filter $filter) use($cityArr){
					$filter->disableIdFilter();
					$filter->column(1 / 4, function ($filter) {
						$filter->equal('uid', '用户UID')->placeholder('请输入uid');
					});
					$filter->column(1 / 4, function ($filter) {
						$filter->equal('nick', '用户昵称')->placeholder('请输入昵称');
					});
					$filter->column(1 / 4, function ($filter) {
						$filter->equal('activity_status', '活动状态')->select(DecoCompanyPreferentialActivity::ACTIVITY_STATUS);
					});
					$filter->column(1 / 4, function ($filter) {
						$filter->equal('activity_type', '活动类型')->select(DecoCompanyPreferentialActivity::ACTIVITY_TYPE);
					});
                    $filter->column(1 / 4, function ($filter) {
                        $filter->equal('check_status', '审核状态')->select(DecoCompanyPreferentialActivity::CHECK_STATUS);
                    });
                    $filter->column(1 / 4, function ($filter) {
                        $filter->equal('is_superior', '优质活动')->select([1=>'是',0=>'否']);
                    });
                    $filter->column(1 / 4, function ($filter) use($cityArr) {
                        $filter->equal('area_id', '城市')->select($cityArr);
                    });
					$filter->expand();
				});

				$grid->column('id', 'ID')->copyable();
				$grid->column('uid', 'uid')->copyable();
				$grid->column('nick', '公司昵称')->copyable();
                $grid->column('city_name', '城市')->width(50);
//				$grid->column('enterprise_name', '公司名称')->copyable();
				$grid->column('activity_type', '活动类型');
				$grid->column('name', '活动名称');
				$grid->column('effect_date', '活动有效期');
				$grid->column('activity_status', '活动状态')->display(function ($title, Grid\Column $column) {
					if ($this->activity_status == '上架') {
						return $column->label('success');
					} else if ($this->activity_status == '下架') {
						return $column->label('danger');
					} else if ($this->activity_status == '违规') {
						return $column->label('warning');
					} else {
						return '';
					}
				});

                $grid->column('check_status', '审核状态')->display(function ($title, Grid\Column $column) {
                    if ($this->check_status == '待审核') {
                        return $column->label('warning');
                    } else if ($this->check_status == '审核通过') {
                        return $column->label('success');
                    } else if ($this->check_status == '审核拒绝') {
                        return $column->label('danger');
                    } else {
                        return '';
                    }
                });

                $grid->column('is_superior', '优质活动')->display(function ($title, Grid\Column $column) {
                    if ($this->is_superior == 1) {
                        return "<span style='width:50px;display: inline-block;'>优质</span>";
                    }
                });
				$grid->column('get_num', '被领取次数');
				$grid->column('data_status', '数据状态')->display(function ($title, Grid\Column $column) {
					if ($this->data_status == '正常') {
						return $column->label('success');
					} else if ($this->data_status == '删除') {
						return $column->label('danger');
					}
				});
				$grid->column('last_edit_time', '最新编辑时间');
				$grid->actions(function (Grid\Displayers\Actions $actions) {
					$actions->disableDelete();
					$actions->disableView();
					$actions->disableEdit();

					if ($actions->row->data_status == '正常') {
						if ($actions->row->activity_status == '上架') {
							$actions->append("<a onclick=\"return confirm('确认将其置为违规活动吗？')\" href=\"violation/" .
								$actions->row->id . "\" class=\"btn btn-sm btn-danger\"><i class=\"fa fa-close\">&nbsp;标为违规</i></a>");
						} elseif ($actions->row->activity_status == '违规') {
							$actions->append("<a href=\"cancelViolation/" .
								$actions->row->id . "\" class=\"btn btn-sm btn-success\"><i class=\"fa fa-check\">&nbsp;取消违规</i></a>");
						}
					}

                    $actions->append('<a href="/admin/DecoCompanyPreferential/check/' . $actions->row->id . '" class="fa fa-check-square-o" style="width: 50px;font-size: 13px;">审核</a>');
				});
			});

		$tab = new Tab();
		$tab->add('活动内容列表', $gridList->render());
		$content->row($tab);
		return $content
			->header('装修公司活动内容')
			->breadcrumb(['text' => '装修公司活动内容列表']);
	}

    public function check(Request $request, Content $content, $id = 0)
    {
        $row = DecoCompanyPreferentialActivity::get("*",['id'=>$id]);
        $info = DecoCompanyAuth::getByUid($row['uid']);
        $row['enterprise_name'] = $info ? $info["enterprise_name"] : "";
        $row['ac_type'] = '';
        if(!empty($row['activity_type'])){
            $row['ac_type'] = DecoCompanyPreferentialActivity::ACTIVITY_TYPE[$row['activity_type']];
        }
        $row['expire_time'] = '';
        if(!empty($row['start_date']) && !empty($row['end_date'])){
            $row['expire_time'] = date("Y.m.d",strtotime($row['start_date'])).'-'.date("Y.m.d",strtotime($row['end_date']));
        }
        if(!empty($row['header_pic'])){
            $row['header_pic'] = ImgUrl::getUrl(ImgUrl::APPTYPE_APP, $row['header_pic'], ImgUrl::IMAGE_SIZE_O_500);
        }
        if(!empty($row['detail_pic'])){
            $detail_pic = explode(',',$row['detail_pic']);
            $pics = [];
            foreach ($detail_pic as $value){
                $pics[] = ImgUrl::getUrl(ImgUrl::APPTYPE_APP, $value, ImgUrl::IMAGE_SIZE_O_500);
            }
            $row['detail_pic'] = $pics;
        }

        $form = new Form($row);
        $tab = new Tab();
        $tab->add('审核', $form);

        $form->hidden('id');
        $form->display('uid', 'UID');
        $form->display('enterprise_name', '公司名称');
        $form->display('name', '活动名称');
        $form->display('ac_type', '活动类型');
        $form->display('expire_time', '有效期');
        $form->divider("活动头图");
        $html = '';
        if ($row['header_pic']) {
            $html .= "<img src='{$row['header_pic']}' style='width:230px;margin:4px 5px;border: 5px solid #ddd;'>";
        }
        $form->html($html);
        $form->divider();
        $form->display('main_explain', '活动说明');
        $form->display('supplement_explain', '补充说明');
        $form->divider("活动图片");
        $html = '';
        if(!empty($row['detail_pic']) && is_array($row['detail_pic'])){
            foreach ($row['detail_pic'] as $item) {
                if ($item) {
                    $html .= "<img src='{$item}' style='width:230px;margin:4px 5px;border: 5px solid #ddd;'>";
                }
            }
        }
        $form->html($html);
        $form->divider();

        $form->radio('is_superior', '优质活动')->options([1 => '是', 0 => '否'])->default(0);

        $form->select('check_status', '审核状态')->setWidth(3, 2)->options(self::CHECK_STATUS_DESC);
        $form->disableReset();

        $form->confirm('确认操作审核吗？');

        $form->action('/admin/DecoCompanyPreferential/submit');

        return $content
            ->header('装修公司活动')
            ->description('活动审核')
            ->breadcrumb(['text' => '活动审核'])
            ->body($tab);
    }

    public function submit(Request $request)
    {
        $params = $request->input();
        unset($params['_token']);
        $info = DecoCompanyPreferentialActivity::get("*",['id'=>$params['id']]);
        $uid = $info['uid'];

        $rows = DecoCompanyPreferentialActivity::get(['id'],['uid'=>$uid,'is_superior'=>DecoCompanyPreferentialActivity::IS_SUPERIOR,'data_status'=>DecoCompanyPreferentialActivity::STATUS_NORMAL]);
        if($rows && $rows['id'] != $params['id'] && $params['is_superior'] == DecoCompanyPreferentialActivity::IS_SUPERIOR){
            $error = new MessageBag([
                'title' => '该公司已存在优质活动'
            ]);
            return back()->withInput()->with(compact('error'));
        }
        $data = [];
        $data['check_status'] = $params['check_status'];
        //审核拒绝时下架活动
        if($data['check_status'] == DecoCompanyPreferentialActivity::CHECK_FAIL){
            $data['activity_status'] = DecoCompanyPreferentialActivity::ACTIVITY_OFFLINE;
        }
        //审核通过时默认上架活动
        $toDay = date('Y-m-d');
        if($data['check_status'] == DecoCompanyPreferentialActivity::CHECK_PASS && $toDay >= $info['start_date'] && $toDay <= $info['end_date']){
            //判断该装修公司是否已上架3个活动
            $upActivityNum = DecoCompanyPreferentialActivity::getUpperNum($uid);
            if($upActivityNum >=3){
                $error = new MessageBag([
                    'title' => '该公司活动已超过最大上架数量'
                ]);
                return back()->withInput()->with(compact('error'));
            }
            $data['activity_status'] = DecoCompanyPreferentialActivity::ACTIVITY_ONLINE;
        }
        $data['is_superior'] = $params['is_superior'];
        $res = DecoCompanyPreferentialActivity::update($data, ['id'=>$params['id']]);
        if ($res) {
            // 同步最新「活动优惠」信息
            Queue::insertQueue('/queue/Decocompany/AsyncDiscountActivity',[
                'uid' => $uid,
            ], Queue::QUEUE_DORAEMON);

            if ($info['activity_status'] == DecoCompanyPreferentialActivity::ACTIVITY_ONLINE && $data['check_status'] == DecoCompanyPreferentialActivity::CHECK_FAIL) {
                // 解除关联问候语
                DesignerGreetingsSet::removeGreetingsBind($uid, $params['id']);
            }

            $success = new MessageBag([
                'title' => '审核成功'
            ]);
            return redirect("/admin/DecoCompanyPreferential/lists")->with(compact('success'));
        } else {
            $error = new MessageBag([
                'title' => '审核失败，请稍后重试'
            ]);
            return back()->withInput()->with(compact('error'));
        }
    }

	// 违规
	public function violation($id)
	{
		$admin_id = Admin::user()->id;
		$admin_name = Admin::user()->username;

		$info = DecoCompanyPreferentialActivity::get('*', [
			'id' => $id
		]);

		if (empty($info)) {
			$error = new MessageBag([
				'title' => '活动不存在'
			]);
			return back()->with(compact('error'));
		}

		$res = DecoCompanyPreferentialActivity::action(function() use ($id, $admin_id, $admin_name) {
			$result = DecoCompanyPreferentialActivity::update([
				'activity_status' => DecoCompanyPreferentialActivity::ACTIVITY_VIOLATION
			], [
				'id' => $id
			]);

			if (empty($result)) {
				return false;
			}

			DecoCompanyPreferentialAudit::insert([
				'activity_id' => $id,
				'op' => '标为违规',
				'admin_id' => $admin_id,
				'admin_name' => $admin_name,
				'operated_at' => time()
			]);

			return true;
		});

		if (empty($res)) {
			$error = new MessageBag([
				'title' => '标记违规失败'
			]);
			return back()->with(compact('error'));
		} else {
			Queue::insertQueue('queue/Sysmsg/Send', [
				'msgCode' => 706,
				'to_uid' => $info['uid'],
				'msgParams' => [
					'activity_name' => $info['name']
				],
			], Queue::QUEUE_DORAEMON);

			// 同步最新「活动优惠」信息
			Queue::insertQueue('/queue/Decocompany/AsyncDiscountActivity',[
				'uid' => $info['uid'],
			], Queue::QUEUE_DORAEMON);

			$success = new MessageBag([
				'title' => '标记违规成功'
			]);
			return back()->with(compact('success'));
		}
	}

	// 取消违规
	public function cancelViolation($id)
	{
		$admin_id = Admin::user()->id;
		$admin_name = Admin::user()->username;

		$res = DecoCompanyPreferentialActivity::action(function() use ($id, $admin_id, $admin_name) {
			$result = DecoCompanyPreferentialActivity::update([
				'activity_status' => DecoCompanyPreferentialActivity::ACTIVITY_OFFLINE
			], [
				'id' => $id
			]);

			if (empty($result)) {
				return false;
			}

			DecoCompanyPreferentialAudit::insert([
				'activity_id' => $id,
				'op' => '取消违规',
				'admin_id' => $admin_id,
				'admin_name' => $admin_name,
				'operated_at' => time()
			]);

			return true;
		});

		if (empty($res)) {
			$error = new MessageBag([
				'title' => '取消违规失败'
			]);
			return back()->with(compact('error'));
		} else {
			$info = DecoCompanyPreferentialActivity::get('*', [
				'id' => $id
			]);
			// 同步最新「活动优惠」信息
			Queue::insertQueue('/queue/Decocompany/AsyncDiscountActivity',[
				'uid' => $info['uid'],
			], Queue::QUEUE_DORAEMON);

			$success = new MessageBag([
				'title' => '取消违规成功'
			]);
			return back()->with(compact('success'));
		}
	}
}
